var roleE2S59_HBRU_II = {
    run: function(creep) {
        //creep.say(creep.memory.building);
        if(creep.store.getUsedCapacity()==0){
            creep.memory.building = true;
        }
        if(creep.store.getFreeCapacity()==0){
            creep.memory.building = false;
        }

        if(creep.memory.building == true){
                //creep.say(321321);
                var sources = creep.room.find(FIND_SOURCES);
                if(creep.harvest(sources[1]) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(sources[1], {reusePath:15});
                }
        } 
        else{
            //存放
            var targetsspawn = creep.room.find(FIND_STRUCTURES, {
                        filter: (structure) => {
                            return ((structure.structureType == STRUCTURE_EXTENSION ||
                                    structure.structureType == STRUCTURE_SPAWN) && 
                                    structure.store.getFreeCapacity(RESOURCE_ENERGY) > 0)||
                                    (structure.structureType == STRUCTURE_TOWER && 
                            structure.store.getFreeCapacity(RESOURCE_ENERGY) > 400);
                        }
                    });
            if(targetsspawn .length > 0) {
                if(creep.transfer(targetsspawn [0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(targetsspawn [0], {reusePath:15});
                }
            }
            //修理
            else{
                var targetsfix = creep.room.find(FIND_STRUCTURES, {
                    filter: (structure) => structure.hits < structure.hitsMax*0.000001
                });
                targetsfix.sort((a,b) => a.hits - b.hits);
                if(targetsfix.length > 0 ) {
                    if(creep.repair(targetsfix[0]) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(targetsfix[0], {reusePath:15});
                        //creep.say('修去');
                    }
                }
                
                else{
                    //建设           
                    var targetsbuild = creep.room.find(FIND_CONSTRUCTION_SITES);
                    if(targetsbuild.length > 0 ) {
                        if(creep.build(targetsbuild[0]) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(targetsbuild[0], {reusePath:15});
                            //creep.say('建去');    //说话测试
                        }
                    }
                    else{
                        //up升级
                        if(creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(creep.room.controller);
                            //creep.say('升去');
                        }
                    } 
                }
            }
        }
	}
};

module.exports = roleE2S59_HBRU_II;